from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.decorators import api_view
from rest_framework.filters import OrderingFilter
from rest_framework.generics import RetrieveAPIView, ListCreateAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from api.models import District
from api.serializers import CarSerializer, RecordSerializer, DistrictSerializer, DistrictDetailSerializer
from api.utils import CarFilterSet, RecordFilterSet
from record.models import Car, Record


@api_view(['GET'])
def get_provinces(request):
    queryset = District.objects.filter(parent__isnull=True)
    serializer = DistrictSerializer(queryset, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def get_districts(request, distid):
    district = District.objects.filter(distid=distid).first()
    serializer = DistrictDetailSerializer(district)
    return Response(serializer.data)


# @method_decorator(decorator=cache_page(timeout=86400, cache='default'), name='get')
class CarView(RetrieveAPIView, ListCreateAPIView):
    """汽车视图集合"""
    queryset = Car.objects.all()
    serializer_class = CarSerializer
    pagination_class = None
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    filterset_class = CarFilterSet
    ordering = ('id', )
    ordering_fields = ('id', 'carno')

    # def get_queryset(self):
    #     owner = self.request.GET.get('owner', '')
    #     ordering = self.request.GET.get('ordering', '').strip()
    #     queryset = Car.objects.filter(owner__contains=owner)
    #     if ordering:
    #         queryset = queryset.order_by(ordering)
    #     return queryset

    def get(self, request, *args, **kwargs):
        if 'pk' in kwargs:
            return RetrieveAPIView.get(self, request, *args, **kwargs)
        return ListCreateAPIView.get(self, request, *args, **kwargs)


# @method_decorator(decorator=cache_page(timeout=300, cache='default'), name='retrieve')
# @method_decorator(decorator=cache_page(timeout=300, cache='default'), name='list')
class RecordViewSet(ModelViewSet):
    """违章记录视图集合"""
    queryset = Record.objects.all().select_related('car')
    serializer_class = RecordSerializer
    throttle_classes = ()
    filter_backends = (DjangoFilterBackend, OrderingFilter)
    ordering = ('-makedate', )
    filterset_class = RecordFilterSet
